
// ===============================================================================================================
// -*- FRAGMENT SHADER -*-
//
// BlinnPhong.frag - GLSL fragment shader.
//
// Copyright (c) 2011 Guilherme R. Lampert
// guilherme.ronaldo.lampert@gmail.com
//
// This code is licenced under the MIT license.
//
// This software is provided "as is" without express or implied
// warranties. You may freely copy and compile this source into
// applications you distribute provided that the copyright text
// above is included in the resulting source code.
//
// ===============================================================================================================

varying vec3 normalVec;
uniform sampler2D textureMap;
uniform int numEnabledLights;
uniform int hasTexture;

void main()
{
	vec3 N;
	vec3 L;
	vec3 H;
	vec3 ambient;
	vec3 diffuse;
	vec3 specular;
	vec3 textureColor;
	vec3 finalColor = vec3(0.0, 0.0, 0.0);

	if (hasTexture == 1)
	{
		// Apply texture, if any
		textureColor = vec3(texture2D(textureMap, gl_TexCoord[0].xy));
	}
	else
	{
		// No texture for this fragment
		textureColor = vec3(1.0, 1.0, 1.0);
	}

	// Do per pixel lighting calculation for all active lights (may be slow)
	for (int i = 0; i < numEnabledLights; ++i)
	{
		N = normalize(normalVec);
		L = normalize(gl_LightSource[i].position.xyz);
		H = normalize(gl_LightSource[i].halfVector.xyz);
 
		ambient = gl_LightSource[i].diffuse.rgb * gl_LightSource[i].ambient.rgb;
		diffuse = gl_LightSource[i].diffuse.rgb * (1.0 - gl_LightSource[i].ambient.rgb) * max(dot(L, N), 0.0);
		specular = gl_LightSource[i].specular.rgb * pow(max(dot(H, N), 0.0), gl_FrontMaterial.shininess);

		diffuse *= textureColor;
		finalColor += (ambient + diffuse + specular);
	}

	gl_FragColor = vec4(finalColor, 1.0);
}
